#!/usr/bin/python

from google.appengine.api import urlfetch
import logging
import datetime
import Warehouse
import re

class parser:

    def __init__(self, box):
        self.box=box
        self.dirty=False

    def isDirty(self):
        return self.dirty

    def getMatch(self, match):
        if match is None:
            return None
        #return match.group(1)
        r=""
        for m in match.groups():
            r+=m
        return r

    def readContext(self, url):
        result = urlfetch.fetch(url)
        if result.status_code == 200:
            return result.content
        return None

    def run(self):
        context = self.readContext(self.box.url)
        if context is None:
            return

        for item,stuff in self.box.stuffs.items():
            b=re.compile(stuff.getpattern())
            match=self.getMatch(b.search(context))
            if match is None:
                logging.error("Bad pattern<%s> of item<%s> at url<%s>",stuff.getpattern(),item,self.box.url)
            else:
                self.box.setitem(item,self.getMatch(b.search(context)))
                if self.dirty is False:
                    # Wow, It is lambda time! 
                    # [lambda, p1, p2] 
                    lam, p1, p2 = stuff.getlambda()
                    val, ref = stuff.getvalue()
                    fun="lambda val,ref,p1,p2: "+lam
                    self.dirty=eval(fun)(val,ref,p1,p2)
        if self.dirty:
            self.box.keepref()
                    

    def report(self):
        if self.dirty is True:
            Content=""
            for item,stuff in self.box.stuffs.items():
                val, ref=stuff.getvalue()
                if item == 'PageUpdateTime':
                    Content+="--->>>Updated "+val+"<<<---\n"
                else:
                    Content+= item+' : '+val+"\n"
            return Content
        else:
            return None
